package com.jisf.driver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jisf.driver.entity.po.User;
import com.jisf.driver.mapper.MenuMapper;
import com.jisf.driver.mapper.UserMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @Classname MyDetailsService
 * @Description TODO
 * @Date 2022/2/20 15:43
 * @Created by jisf：【429627912@qq.com】
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user = userMapper.selectOne(queryWrapper);
        if (StringUtils.isBlank(username)){
            throw new DisabledException("输入用户名为空");
        }
        if (Objects.isNull(user)){
            throw new InternalAuthenticationServiceException("账号不存在");
        }
        if (user.getDelFlag().getCode() != 0){
            throw new InternalAuthenticationServiceException("该账号已注销");
        }
        if (user.getStatus().getCode() != 0){
            throw new InternalAuthenticationServiceException("该账号未审核");
        }
        //获取权限信息
        List<String> auths = menuMapper.selectPermsByUserId(user.getId());

        return new UserDetailsImpl(user,auths);
    }
}
